package com.icesoft.base.manager.controller.manager;

import com.icesoft.base.manager.entity.security.RelSysRoleOrg;
import com.icesoft.base.manager.entity.system.SysOrg;
import com.icesoft.base.manager.service.security.RelSysRoleOrgService;
import com.icesoft.base.manager.service.manager.RelSysOrgOwnerService;
import com.icesoft.base.manager.service.system.SysOrgService;
import com.icesoft.core.common.helper.Resp;
import com.icesoft.core.common.helper.TreeBean;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 组织机构权限管理
 * */
@RequestMapping("manager/org")
@RestController
@AllArgsConstructor
public class SysOrgManagerController {
    private SysOrgService sysOrgService;
    private RelSysOrgOwnerService relSysOrgOwnerService;
    private RelSysRoleOrgService relSysRoleOrgService;

    /**
     * 全部部门树
     * */
    @GetMapping("adminTree")
    public Resp<List<TreeBean>> adminTree(Integer companyId) {
        List<SysOrg> orgs;
        if (companyId != null) {
            orgs = sysOrgService.findByCompanyId(companyId);
        } else {
            orgs = sysOrgService.findAll();
        }
        Resp<List<TreeBean>> resp = new Resp<>();
        resp.setData(sysOrgService.toTreeBean(orgs));
        return resp;
    }
    /**
     * 部门拥有的查询范围树
     * */
    @GetMapping("ownerOrgTree")
    public Resp<List<TreeBean>> ownerOrgTree(@RequestParam int orgId) {
        List<SysOrg> orgs = sysOrgService.findAll();
        List<Integer> ownerOrgIds = relSysOrgOwnerService.findOwnerOrgIdsByOrgId(orgId);
        Resp<List<TreeBean>> resp = new Resp<>();
        resp.setData(sysOrgService.toTreeBean(orgs, ownerOrgIds));
        return resp;
    }
    /**
     * 角色拥有的查询范围树
     * */
    @GetMapping("roleOrgTree")
    public Resp<List<TreeBean>> roleOrgTree(@RequestParam int roleId) {
        List<SysOrg> orgs = sysOrgService.findAll();
        List<Integer> ownerOrgIds = relSysRoleOrgService.findByRoleId(roleId).stream().map(RelSysRoleOrg::getOrgId).collect(Collectors.toList());
        Resp<List<TreeBean>> resp = new Resp<>();
        resp.setData(sysOrgService.toTreeBean(orgs, ownerOrgIds));
        return resp;
    }

    /**
     * 修改部门查询范围接口
     * */
    @PostMapping("updateOrgQx")
    public Resp<?> updateOrgQx(@RequestParam Integer orgId, @RequestParam List<Integer> ownerOrgIds) {
        relSysOrgOwnerService.updateOwnerOrg(orgId, ownerOrgIds);
        return new Resp<>();
    }
}
